package day11;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;

/**
 * <a href="https://leetcode.cn/problems/valid-parentheses/">20.有效的括号</a>
 *
 * @author admin
 */
public class Answer {

    public static void main(String[] args) {
//        String s = "{(){[()()]}{}}";
        // 1 - 4 - 6
        // 8
        String s = "(([]){})";
//        String s = "[({])}";
//        String s = "([}}])";
        Answer answer = new Answer();
        System.out.println(answer.isValid(s));
        System.out.println(answer.isValid1(s));
    }

    public boolean isValid(String s) {
        int length = s.length();
        if (length == 1) {
            return false;
        }
        if (length % 2 != 0) {
            return false;
        }
        String[] split = s.split("");
        List<String> list = new ArrayList<>(List.of(split));
        return arrList(list).size() == 0;
    }

    public boolean isValid1(String s) {
        int length = s.length();
        if (length == 1) {
            return false;
        }
        if (length % 2 != 0) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (getChar(c) != 'a') {
                stack.push(getChar(c));
                continue;
            }
            if (stack.isEmpty()) return false;
            if (c == stack.peek()) {
                stack.pop();
            } else {
                return false;
            }

        }
        return stack.empty();
    }

    public char getChar(char c) {
        switch (c) {
            case '(':
                return ')';
            case '{':
                return '}';
            case '[':
                return ']';
        }
        return 'a';
    }

    public List<String> arrList(List<String> list) {
        List<String> origin = new ArrayList<>(list);
        int length = list.size();
        for (int i = 0; i < length - 1; i++) {
            if (list.get(i) == null) continue;
            if (list.get(i + 1) == null) continue;
            int a = getASC(list.get(i));
            int b = getASC(list.get(i + 1));
            if (compare(a, b)) {
                list.set(i, null);
                list.set(i + 1, null);
            }
        }
        list.removeIf(Objects::isNull);
        if (list.equals(origin)) {
            return list;
        }
        return arrList(list);
    }

    public int getASC(String a) {
        byte[] bytes = a.getBytes(StandardCharsets.US_ASCII);
        return bytes[0];
    }

    public boolean compare(int a, int b) {
        return a + 1 == b || a + 2 == b;
    }
}
